﻿function PagerModel(itemsAccessor) {

    var pageNumber = ko.observable(1);

    var pageSize = ko.observable(10);

    var pagesCount = ko.computed(function () {
        var ps = pageSize();
        var count = itemsAccessor().length;
        return Math.floor((count + ps - 1) / ps);
    });

    var itemsCount = ko.computed(function () {
        var all = itemsAccessor();
        return all.length;
    });

    var items = ko.computed(function () {
        var pn = pageNumber();
        var ps = pageSize();
        var start = (pn - 1) * ps;
        var end = start + ps;

        var all = itemsAccessor();
        start = Math.min(start, all.length);
        end = Math.min(end, all.length);

        var res = [];
        for (var i = start; i < end; i++) {
            var item = all[i];
            res.push(item);
        }
        return res;
    });

    var neighbourPages = ko.computed(function () {
        var res = [];
        var current = pageNumber();
        var count = pagesCount();

        res.push(current);

        var resCount = 7;
        for (var i = 0; (i < resCount * 2) && res.length < resCount; i++) {
            var page = current;
            if (i % 2 == 0) {
                page += 1 + i / 2;
            } else {
                page -= 1 + (i - 1) / 2;
            }
            if (page >= 1 && page <= count) {
                if (page > current) {
                    res.push(page);
                } else {
                    res.unshift(page);
                }
            }
        }

        return res;
    });

    var isFirst = ko.computed(function () {
        return pageNumber() <= 1;
    });

    var isLast = ko.computed(function () {
        return pageNumber() >= pagesCount();
    });

    function goTo(page) {
        pageNumber(page);
    }

    function goToFirst() {
        pageNumber(1);
    }

    function goToLast() {
        pageNumber(pagesCount());
    }

    itemsAccessor.subscribe(goToFirst);

    this.pageNumber = pageNumber;
    this.pagesCount = pagesCount;
    this.pageSize = pageSize;
    this.items = items;
    this.itemsCount = itemsCount;
    this.neighbourPages = neighbourPages;
    this.goTo = goTo;
    this.goToFirst = goToFirst;
    this.goToLast = goToLast;
    this.isFirst = isFirst;
    this.isLast = isLast;
}